package com.es.easystoragesimulatedata.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;

@Slf4j
@Component
public class DatabaseConfig implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        try {
            // 测试数据库连接
            try (Connection connection = dataSource.getConnection()) {
                log.info("数据库连接成功！");
                log.info("数据库URL: {}", connection.getMetaData().getURL());
                log.info("数据库产品名称: {}", connection.getMetaData().getDatabaseProductName());
                log.info("数据库版本: {}", connection.getMetaData().getDatabaseProductVersion());
            }

            // 测试SQL查询
            String result = jdbcTemplate.queryForObject("SELECT 'Hello Database!' as message", String.class);
            log.info("数据库查询测试成功: {}", result);

        } catch (Exception e) {
            log.error("数据库连接失败: {}", e.getMessage(), e);
        }
    }
}
